# -*- coding: utf-8 -*-
"""
企业微信工具模块
负责文件上传和消息发送功能
"""
import requests
import time
import os
from config_utils import load_and_validate_config

# 加载配置
CONFIG = load_and_validate_config()


def upload_media(file_path, webhook_key='your_webhook_key_here'):
    """
    上传文件到企业微信服务器并获取Media ID
    
    :param file_path: 要上传的文件的本地路径
    :param webhook_key: 企业微信机器人的Webhook key
    :return: Media ID，如果上传失败则返回None
    """
    url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={webhook_key}&type=file"
    
    # 获取文件名
    file_name = file_path.split('\\')[-1]
    
    try:
        with open(file_path, 'rb') as file:
            files = {
                'media': (file_name, file, 'application/octet-stream')
            }
            
            response = requests.post(url, files=files)
            
            if response.status_code == 200:
                result = response.json()
                if result.get('errcode') == 0:
                    return result.get('media_id')
                else:
                    print(f"上传文件失败: {result.get('errmsg')}")
            else:
                print(f"上传文件失败: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"上传文件发生错误: {e}")
    return None


def send_file_to_qywx(file_path, webhook_key='your_webhook_key_here'):
    """
    使用企业微信机器人发送文件
    
    :param file_path: 要发送的文件的本地路径
    :param webhook_key: 企业微信机器人的Webhook key
    """
    # 上传文件获取media_id
    media_id = upload_media(file_path, webhook_key)
    if not media_id:
        print("获取media_id失败，无法发送文件")
        return
    
    # 构建文件消息
    data = {
        "msgtype": "file",
        "file": {
            "media_id": media_id
        }
    }
    
    # 构建完整的webhook URL
    webhook_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={webhook_key}"
    
    try:
        # 发送文件
        response = requests.post(webhook_url, json=data)
        
        # 检查响应状态码
        if response.status_code == 200:
            result = response.json()
            if result.get('errcode') == 0:
                print("文件发送成功")
                # 发送成功后删除文件
                try:
                    os.remove(file_path)
                    print(f"文件 {file_path} 已成功删除")
                except Exception as e:
                    print(f"删除文件失败: {e}")
            else:
                print(f"文件发送失败: {result.get('errmsg')}")
        else:
            print(f"文件发送失败: {response.status_code} - {response.text}")
    except Exception as e:
        print(f"发送文件发生错误: {e}")
    
    # 避免发送频率过快
    time.sleep(20)